package com.vitaf.cash.app.common

import android.view.View
import com.vitaf.cash.app.BuildConfig
import com.vitaf.cash.app.R
import com.vitaf.cash.app.VitafCashApplication
import com.vitaf.cash.app.base.VitafBaseActV2
import com.vitaf.cash.app.configs.VitafConfigs
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.VitafEventSubscriber
import com.vitaf.cash.app.request.HttpHelper
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.dialog.VitafCustomerDlog
import com.vitaf.cash.app.ui.dialog.VitafTipsDlog
import com.vitaf.cash.app.utils.VitafTitleBarUtil
import com.vitaf.cash.app.utils.log.VitafLog
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

/**
 * CommonActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:32
 * @Annotation：
 */
abstract class VitafComActV2: VitafBaseActV2(), VitafEventSubscriber, IVitafComViewV2,EasyPermissions.PermissionCallbacks {
    //是否记录埋点
    private var isPageViewRecorded = false

    // 获取页面名称，子类必须实现
    protected abstract val pageName: String
    // 是否启用页面埋点（默认启用）
    protected open val enablePageTrack: Boolean = true

    var errorDialog: VitafTipsDlog? = null
    //客服
    var customerDialog: VitafCustomerDlog? = null

    override fun getAct(): VitafComActV2 {
        return this
    }

    /**
     * 返回
     */
    fun onClickBack() {
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.BACK_CLICK, pageName)
        super.onBackAction()
    }

    /**
     * 客服
     */
    fun onClickCustomer(){
        onClickCustomer(pageName)
    }

    /**
     * 客服
     */
    fun onClickCustomer(remark: String = pageName){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER, remark)
        showCustomerDialog(remark)
    }

    /**
     * 设置Top padding
     */
    fun setViewPaddingTopStatusBarHeight(view: View?,topPadding: Int = VitafTitleBarUtil.getStatusBarHeight()){
        view?.let {
            view.setPadding(0,topPadding,0,0)
        }
    }

    /**
     * 错误提示
     */
    fun showErrorTipsDialog(tips: String,eventRemark: String = ""){
        if (errorDialog == null){
            errorDialog = VitafTipsDlog(this,eventRemark)
        }
        errorDialog?.let { dialog ->
            if (dialog.isShowing){
                return
            }
            dialog.setOnClick(object : VitafTipsDlog.IDialogCallback{
                override fun onClick(view: View?) {

                }
            })
            dialog.show()
            dialog.isGombeCreditKindTipsDoubleButton(false)
            dialog.setGombeCreditKindTipsMsgText(tips)
        }
    }

    /**
     * 客服
     */
    fun showCustomerDialog(remark: String = pageName){
        if (customerDialog == null){
            customerDialog = VitafCustomerDlog(this)
                .setGombeCreditCustomerEventRemark(remark)
                .setGombeCreditCustomerClickCallback(object : VitafCustomerDlog.IDialogCallback{
                    override fun onGombeCreditCallPhoneClick(phoneNumber: String) {
                    }
                    override fun onGombeCreditCopyEmailClick(email: String) {
                    }
                    override fun onGombeCreditFeedbackClick() {//Feedback
                    }
                })
            customerDialog?.setCancelable(true)
            customerDialog?.setCanceledOnTouchOutside(true)
        }
        customerDialog?.show()
    }

    /**
     * 接口请求失败提示
     */
    fun showRequestErrorDialog(errorData: JSONObject){
        if (errorDialog == null){
            errorDialog = VitafTipsDlog(this)
        }
        errorDialog?.let {
            if (it.isShowing){
                return
            }
            it.setOnClick(object : VitafTipsDlog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.buttonConfirm){
                    }
                }
            })
            it.addGombeCreditKindTipsEventRemark("network error")
            it.setCancelable(true)
            it.setCanceledOnTouchOutside(false)
            it.show()
            it.isGombeCreditKindTipsDoubleButton(true)
            it.setGombeCreditKintTipsButtonConfirmText(getString(R.string.vitaf_btn_try_again))
            it.setGombeCreditKindTipsMsgText(getString(R.string.vitaf_dlog_network_error))
        }
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        HttpHelper.post(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                callback.onRequestSuccess(data)
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                showVitafToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
            }
        })
    }

    /**
     * 添加埋点
     */
    fun addEventPointRequestAction(eventName: String, eventRemark: String? = "") {
        HttpHelper.addPoint(eventName,eventRemark)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: VitafEventData){
        VitafCashApplication.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onVitafPublishEvent(event: VitafEventData) {
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        VitafLog.e("onPermissionsGranted, code: $requestCode , permissions : $perms")
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        VitafLog.e("onPermissionsDenied code: $requestCode , permissions : $perms")
    }

    override fun onStart() {
        super.onStart()
//        HttpHelper.setTag(this)
        VitafCashApplication.app.publisher.register(this)
    }

    override fun onResume() {
        super.onResume()
//        NetworkManager.onActivityResumed(this)
        if (!isPageViewRecorded) {
            isPageViewRecorded = true
            if (enablePageTrack){
                addEventPointRequestAction("${VitafConfigs.GOMBECREDIT_APPNAME}_${pageName}_start".uppercase())
            }
        }
    }

    override fun onPause() {
        super.onPause()
        customerDialog?.let {
            if (it.isShowing){
                it.dismiss()
            }
        }
        errorDialog?.dismiss()
        if (isFinishing) {
            if (enablePageTrack){
                addEventPointRequestAction("${VitafConfigs.GOMBECREDIT_APPNAME}_${pageName}_end".uppercase())
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        customerDialog = null
        errorDialog = null
        HttpHelper.cancelTag(this)
        VitafCashApplication.app.publisher.detach(this)
//        NetworkManager.unregisterActivity(this)
    }
}